import re
import os
import requests
from lxml import etree
import hashlib
import time
import random
import json
import html
import execjs  # 必须，需要先用pip 安装，用来执行js脚本
from urllib.parse import quote
import urllib3
urllib3.disable_warnings()
class Data(object):
    # 初始化中给对象属性赋值
    def __init__(self,srcName , enValue):
        self.srcName = srcName
        self.enValue = enValue

mengguUrl="http://mt.utibet.edu.cn/mt"
googleUrl="https://translate.google.cn/translate_a/single?client=webapp&sl=zh-CN&tl=en&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&otf=2&ssel=3&tsel=0&kc=1&tk=517592.87345&q="
header={'User-Agent':  'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
                      ,'Referer':mengguUrl,'Accept-Encoding': 'gzip, deflate','Accept-Language': 'zh-CN,zh;q=0.9',
        'Content-Type': 'text/html; charset=utf-8'}

basePath=os.path.abspath('.')
logList=[]
def requestFromTibet(word):
    param = {'src': word, 'tgt': '', 'lang': 'ct'}
    respone = requests.post(url=mengguUrl, headers=header, data=param)
    respone.encoding = "utf-8"
    html = etree.HTML(respone.text, etree.HTMLParser(), )
    result1 = html.xpath('//textarea[@name="src"]/text()')  # 获取a节点下的内容
    result2 = html.xpath('//*[@id="txt2"]/text()')  # 获取a节点下的内容
    print(result1[0]+"-"+result2[0]+"\n")
    logList.append(result1[0]+"-"+result2[0]+"\n")
    return Data(result1[0],result2[0])

def requestFromGoogle():
    word = "你好"
    respone = requests.get(url=googleUrl + word, headers=header)
    respone.encoding = "utf-8"
    html = etree.HTML(respone.text, etree.HTMLParser(), )
    print(respone.text+"\n")
    """result1 = html.xpath('//textarea[@name="src"]/text()')  # 获取a节点下的内容
    result2 = html.xpath('//*[@id="txt2"]/text()')  # 获取a节点下的内容
    print(os.path.abspath('.'))
    file = open(os.path.abspath('.') + '/books.txt', 'w+', encoding="utf-8")

    for s in result1:
        print(s)
        file.write(s)
    for s in result2:
        print(s)
        file.write(s)
    print(result2)
    file.close()"""
##############################
# 用来判断是否需要打印日志
debug = False

class Py4Js:

    def __init__(self):
        self.ctx = execjs.compile(""" 
            function TL(a) { 
                var k = ""; 
                var b = 406644; 
                var b1 = 3293161072;       
                var jd = "."; 
                var $b = "+-a^+6"; 
                var Zb = "+-3^+b+-f";    
                for (var e = [], f = 0, g = 0; g < a.length; g++) { 
                    var m = a.charCodeAt(g); 
                    128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023), 
                    e[f++] = m >> 18 | 240, 
                    e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224, 
                    e[f++] = m >> 6 & 63 | 128), 
                    e[f++] = m & 63 | 128) 
                } 
                a = b; 
                for (f = 0; f < e.length; f++) a += e[f], 
                a = RL(a, $b); 
                a = RL(a, Zb); 
                a ^= b1 || 0; 
                0 > a && (a = (a & 2147483647) + 2147483648); 
                a %= 1E6; 
                return a.toString() + jd + (a ^ b) 
            };      
            function RL(a, b) { 
                var t = "a"; 
                var Yb = "+"; 
                for (var c = 0; c < b.length - 2; c += 3) { 
                    var d = b.charAt(c + 2), 
                    d = d >= t ? d.charCodeAt(0) - 87 : Number(d), 
                    d = b.charAt(c + 1) == Yb ? a >>> d: a << d; 
                    a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d 
                } 
                return a 
            }
        """)

    def get_tk(self, text):
        return self.ctx.call("TL", text)


def build_url(text, tk, tl='zh-CN'):
    """
    需要用转URLEncoder
    :param text:
    :param tk:
    :param tl:
    :return:
    """
    return 'https://translate.google.cn/translate_a/single?client=webapp&sl=auto&tl=' + tl + '&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&source=btn&ssel=0&tsel=0&kc=0&tk=' \
           + str(tk) + '&q=' + quote(text, encoding='utf-8')


def translate(js, text, tl='zh-CN'):
    """
    tl为要翻译的语言
    de：德语
    ja：日语
    sv：瑞典语
    nl：荷兰语
    ar：阿拉伯语
    ko：韩语
    pt：葡萄牙语
    zh-CN：中文简体
    zh-TW：中文繁体
    """

    header = {
        'authority': 'translate.google.cn',
        'method': 'GET',
        'path': '',
        'scheme': 'https',
        'accept': '*/*',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9,ja;q=0.8',
        # 'cookie': '_ga=GA1.3.110668007.1547438795; _gid=GA1.3.791931751.1548053917; 1P_JAR=2019-1-23-1; NID=156=biJbQQ3j2gPAJVBfdgBjWHjpC5m9vPqwJ6n6gxTvY8n1eyM8LY5tkYDRsYvacEnWNtMh3ux0-lUJr439QFquSoqEIByw7al6n_yrHqhFNnb5fKyIWMewmqoOJ2fyNaZWrCwl7MA8P_qqPDM5uRIm9SAc5ybSGZijsjalN8YDkxQ',
         'cookie':'_ga=GA1.3.110668007.1547438795; _gid=GA1.3.1522575542.1548327032; 1P_JAR=2019-1-24-10; NID=156=ELGmtJHel1YG9Q3RxRI4HTgAc3l1n7Y6PAxGwvecTJDJ2ScgW2p-CXdvh88XFb9dTbYEBkoayWb-2vjJbB-Rhf6auRj-M-2QRUKdZG04lt7ybh8GgffGtepoA4oPN9OO9TeAoWDY0HJHDWCUwCpYzlaQK-gKCh5aVC4HVMeoppI',
        # 'cookie': '',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64)  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36',
        'x-client-data': 'CKi1yQEIhrbJAQijtskBCMG2yQEIqZ3KAQioo8oBCL+nygEI7KfKAQjiqMoBGPmlygE='
    }
    url = build_url(text, js.get_tk(text), tl)
    res = []
    try:
        r = requests.get(url, headers=header,verify=False)
        result = json.loads(r.text)
        r.encoding = "UTF-8"
        ''' if debug:
            print(r.url)
            print(r.headers)
            print(r.request.headers)
            print(result)'''

        res = result[0]
        if res is None:
            if result[7] is not None:
                # 如果我们文本输错，提示你是不是要找xxx的话，那么重新把xxx正确的翻译之后返回
                try:
                    correct_text = result[7][0].replace('<b><i>', ' ').replace('</i></b>', '')
                    if debug:
                        print(correct_text)
                    correct_url = build_url(correct_text, js.get_tk(correct_text), tl)
                    correct_response = requests.get(correct_url)
                    correct_result = json.loads(correct_response.text)
                    res = correct_result[0]
                except Exception as e:
                    if debug:
                        print(e)
                    res = []

    except Exception as e:
        res = []
        if debug:
            print(e)
    finally:
        return res


def get_translate(word, tl):
    js = Py4Js()
    translate_result = translate(js, word, tl)
    print(translate_result)
    logList.append(translate_result)
    if len(translate_result) !=0:
        s=translate_result[0]
        if len(s) !=0:
            result=s[0]

            print(word+"-"+result)
            return Data(word, result)

##############################
appid = "20200109000374241";
secretKey = "kZAoQDjYfa5MNYqQXmeZ";

def requestFromBaidu(word, fromS, to):
    salt = random.randint(32768, 65536)
    sign = appid + word + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()

    url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + word + "&from=" + fromS\
    +"&to=" + to + "&appid=" + appid + "&salt=" + str(salt)  + "&sign=" +sign
    respone = requests.get(url=url, headers=header)
    respone.encoding = "utf-8"
    print(respone.text)
    logList.append(respone.text)
    try:
        jsonS=json.loads(respone.text)
        trans_result=jsonS["trans_result"]
        srcStr= trans_result[0]["src"]
        dstStr= trans_result[0]["dst"]
        print(srcStr+"-"+dstStr+"\n")
        logList.append(srcStr+"-"+dstStr+"\n")
        return Data(srcStr,dstStr)
    except:
        print("解析失败")



def readText(filePath):
    with open(filePath,"r",encoding="utf-8") as file:
        return file.read()

def getStringList(filePath):
    try:
        xml =  etree.parse(filePath)
        root_node = xml.getroot()
        resources = xml.xpath('//string/text()')
        return resources
    except:
        print("文件不存在")

def createEnFile(lang,eng):
    if enResultList !=None and len(enResultList)!=0:
        enpath = basePath + "\\"+eng+"\\vaules-"+lang
        enFile = enpath +"\strings.xml"
        if not os.path.exists(enpath):
            os.makedirs(enpath)
        newlines = []
        with open(basePath+"\strings.xml","r",encoding="utf-8") as rf:
            lines=rf.readlines()
        for line in lines:
            r=re.search(">.*<",line)
            if r !=None and len(r.string)!=0:
                oldValue=r.group().replace(">",'').replace("<",'')
                #enResultList被lxml解析过，old字符也要解析实体字符 如&#xx -> ...
                tmep =oldValue
                newValue = replaceValue(html.unescape(tmep.strip()), enResultList);
                if  len(newValue) != 0:
                    line= line.replace(oldValue, newValue)

            newlines.append(line)
        with open(enFile, "w",encoding="utf-8") as wf:
            wf.writelines(newlines)

def replaceValue(name,list):
    for i in list:
        if name ==i.srcName:
            return i.enValue
    return ''


enResultList= []
count =0;
def createTagerLang(lang,eng):
    global count
    for word in list:
        if eng=="google":
            if lang == 'bo':
                data = enResultList.append(requestFromTibet(word))
                if data != None:
                    enResultList.append(data)
            else:
                data = get_translate(word,  lang)
                if data != None:
                    enResultList.append(data)
                    time.sleep(3)
        else:
            if lang == 'bo':
                data = enResultList.append(requestFromTibet(word))
                if data != None:
                    enResultList.append(data)
            else:
                data = requestFromBaidu(word, "auto", lang)
                if data != None:
                    enResultList.append(data)
                    time.sleep(1)
        count = count + 1
    if count == len(list):
        createEnFile(lang,eng)
print("#### 介绍\n")

print("i18n for Android\n")

print("1.将要翻译资源文件(strings.xml)复制到当前目录下\n")

print("2.等待翻译完成，输出文件为当前目录baidu/values-xx\n")

print("3.数据来源百度翻译、谷歌翻译，藏文http://mt.utibet.edu.cn/mt\n")

print("4.若win下结果显示乱码请复制结果到支持该语种的系统中显示\n")

print("5.由于接口限制/人机验证，每查询会间隔一段时间\n")

print("6.谷歌翻译请开启vpn(全局模式),并注意网络是否畅通\n")

print("7.翻译结果仅供参考请自行校验\n")

#os.system('pause') #按任意键继续
langs = []
l = input("请输入要翻译的语言如jp，不输入默认输出en、bo、ko、ru"+"\n");

if l != None and l!='':
    langs=[l]
else:
    langs = ["en", 'bo', 'kor', 'ru']

list=getStringList(basePath+"\strings.xml")
energin=["baidu","google"]
if list !=None:
    for eng in energin:
        if eng =="baidu":
            print("开始百度\n")
        else:
            print("开始谷歌\n")
        for i in langs:
            count=0
            enResultList = []
            createTagerLang(i,eng)
with open(basePath+"\log.txt","w",encoding="utf-8") as logFile:
    for log in logList:
        if log !=None and log!='':
            logFile.write(log+"\n\n")
os.system('pause') #按任意键继续